/**
 * Created by zoulu on 15/10/14.
 */

var Manage = {
	init: function() {
		Manage.get_data();
		$(".pagination li a").click(function() {
			var page = $(this).attr("page");
			var size = 10;
			Manage.get_data(page, size);
			Common.init_pagination(page);
		});
		$("#data_table tbody").find("a[name='delete_job']").click(Manage.delete_job);

	},
	get_data: function(page, size) {
		if (page == undefined) {
			page = 0;
		}
		if (size == undefined) {
			size = 10;
		}
		ajax("/jobs/list", {
			"since_id": page,
			"size": size
		}, callback_init_table);
	},
	delete_job: function() {
		var job_id = $(this).attr("job_id");


		if (confirm("确定要取消课程?")) {

			ajax("/jobs/cancel", {
				"job_id": job_id,

			}, success);
		}
	},
	init_table: function(result) {
		if (result != null && result.data != null && result.data.jobs.length > 0) {
			var tbody = $("#data_table tbody");
			tbody.empty();
			var jobs = result.data.jobs;
			var schools = result.data.schools;
			var users = result.data.users;
			var teachers = result.data.teachers;
			var schoolsmap = new Map();

			var usersmap = new Map();
			for (var i = 0; i < schools.length; i++) {
				var school = schools[i];
				schoolsmap.put(school.id, school.name);
			}
			for (var i = 0; i < users.length; i++) {
				var user = users[i];
				usersmap.put(user.id, user.name);
			}
			if (null != teachers) {
				var teacher = teachers[i];
				teachersmap.put(teacher.id, teacher.name);
			}

			var trs = "";
			for (var i = 0; i < jobs.length; i++) {
				var job = jobs[i];
				trs += ("<tr>");
				var status = "";
				if (job.status == 0) {
					status = "正常";
				}
				if (job.status == 1) {
					status = "已取消";
				}

				var remark = ("<td>" + job.remark + "</td>");
				var owner = ("<td>" + usersmap.get(job.owner_id) + "</td>");
				var status = ("<td>" + status + "</td>");
				var candidates_count = ("<td>" + job.candiates_count + "</td>");
				var created_at = ("<td>" + formatDate(job.created_at) + "</td>");
				if (0 != job.teacher_id) {
					var teacher = ("<td>" + usersmap.get(job.teacher_id) + "</td>");
				} else {
					var teacher = ("<td></td>");
				}
				var operate = ("<td>");
				if (job.status == 0) {
					operate += ("<a job_id='" + job.id + "'  name='delete_job' href='javascript:void(0)'>取消课程</a> ");
					if (0 == job.teacher_id) {
						operate += ("&nbsp;&nbsp;<a name='select_lessons' href='./job_teacher.html?job_id=" + job.id + "'>选择教练</a>");
					}
				}
				operate += ("</td>");
				trs += (teacher + owner + candidates_count + remark + status + created_at + operate);
				trs += ("</tr>");
			}
			tbody.append(trs);

		}
	}
};

function callback_init_table(result) {
	Manage.init_table(result);
}

function success(result) {
	if (result != null && result.code == 0) {
		window.location.reload();
	} else {
		alert("操作失败，请刷新页面重试！");
	}
}

function callback_init_class(result) {
	Manage.init_class(result);
}

$(function() {
	Manage.init();
})